//
//  MeishiZhuantiViewController.m
//  B段项目
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 徐茂怀. All rights reserved.
//
#import "MeishiZhuantiViewController.h"
#import "FitHeader.h"
#import "FoodProjectCell.h"
#import "XMHNetWorkongMethods.h"
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>
#import "FoodProjectModel.h"
#import <MBProgressHUD.h>
#import "FoodProjectDetailViewController.h"

static NSString *identifier = @"cell";
@interface MeishiZhuantiViewController ()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,assign)NSInteger p;
@property(nonatomic,strong)MBProgressHUD *HUDView;
@property(nonatomic, strong)UIAlertController *alertController;
@end

@implementation MeishiZhuantiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"美食专题";
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
    _p = 1;
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _p = 1;
        [_dataArray removeAllObjects];
        NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString *path = [str stringByAppendingPathComponent:@"美食专题"];
        NSFileManager *manager = [NSFileManager defaultManager];
        [manager removeItemAtPath:path error:nil];
        [self getData];
    }];
    
    _tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _p++;
        [self getData];
    }];
    [_tableView.header beginRefreshing];
}

-(void)loadView
{
    [super loadView];
    [self getData];
    _dataArray = [NSMutableArray array];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UITableView alloc]init];
    [self.view addSubview:_tableView];
    
    _HUDView = [[MBProgressHUD alloc]initWithView:self.view];
    [_HUDView setMode:MBProgressHUDModeIndeterminate];
    [_HUDView show:YES];
    [self.view addSubview:_HUDView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
#pragma mark cell样式
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoodProjectCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[FoodProjectCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (_dataArray.count == 0) {
        return cell;
    }else {
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.titleLabel.text = [_dataArray[indexPath.row] title];
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[_dataArray[indexPath.row] thumb]] placeholderImage:[UIImage imageNamed:@"老鼠"]];
    return cell;
    }
}

#pragma mark cell点击
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArray.count) {
        
        self.hidesBottomBarWhenPushed = YES;
        FoodProjectDetailViewController *fpdVC = [[FoodProjectDetailViewController alloc]init];
        fpdVC.jianjie = [NSString stringWithString:[_dataArray[indexPath.row] jianjie]];
        fpdVC.ID = [_dataArray[indexPath.row] iD];
        fpdVC.titleString = [_dataArray[indexPath.row] title];
        fpdVC.thumbString = [_dataArray[indexPath.row] thumb];
        [self.navigationController pushViewController:fpdVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    }
    else
    {
        [self getData];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240 * FitWidth;
}
#pragma mark cell将要出现效果
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CATransform3D transform = CATransform3DIdentity;
    transform = CATransform3DScale(transform, .01f, .01f, 1);
    UIView *backView = [cell contentView];
    backView.layer.transform = transform;
    backView.layer.opacity = 0.2f;
    [UIView animateWithDuration:0.3f animations:^{
        backView.layer.transform = CATransform3DIdentity;
        backView.layer.opacity = 1.0f;
    }];
}

-(void)getData
{
    
    NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *path = [str stringByAppendingPathComponent:@"美食专题"];
    if (_p == 1 && [NSDictionary dictionaryWithContentsOfFile:path]) {
        NSDictionary *data = [NSDictionary dictionaryWithContentsOfFile:path];
        NSArray *array = [data objectForKey:@"results"];
        for (NSDictionary *dic in array) {
            FoodProjectModel *fpModel = [[FoodProjectModel alloc]init];
            [fpModel setValuesForKeysWithDictionary:dic];
            [_dataArray addObject:fpModel];
            [_tableView reloadData];
            [_tableView.header endRefreshing];
            [_tableView.footer endRefreshing];
            [_HUDView removeFromSuperview];

    }
    }
    else
    {
    [XMHNetWorkongMethods getDataVyString:[NSString stringWithFormat:@"http://ibaby.ipadown.com/api/food/food.topic.list.php?p=%ld&pagesize=12&order=views", _p] BodyString:nil WithDataBlock:^(id data) {
        if (_p == 1) {
            NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
            NSString *path = [str stringByAppendingPathComponent:@"美食专题"];
            NSFileManager *manager = [NSFileManager defaultManager];
            [manager createFileAtPath:path contents:data attributes:nil];
        }
        NSArray *array = [data objectForKey:@"results"];
        for (NSDictionary *dic in array) {
            FoodProjectModel *fpModel = [[FoodProjectModel alloc]init];
            [fpModel setValuesForKeysWithDictionary:dic];
            [_dataArray addObject:fpModel];
            [_tableView reloadData];
            [_tableView.header endRefreshing];
            [_tableView.footer endRefreshing];
            [_HUDView removeFromSuperview];
        }
    } WithFailure:^(NSError *error) {
        _alertController = [UIAlertController alertControllerWithTitle:@"网络错误" message:@"请检查网络" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:_alertController animated:YES completion:nil];
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [_HUDView removeFromSuperview];
            [_alertController removeFromParentViewController];
            [_tableView.header endRefreshing];
            [_tableView.footer endRefreshing];
        }];
        UIAlertAction *going = [UIAlertAction actionWithTitle:@"继续加载" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self getData];
            [_alertController removeFromParentViewController];
        }];
        [_alertController addAction:going];
        [_alertController addAction:ok];
    }
     ];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
